import * as docx from 'docx-preview';
import PizZip from 'pizzip';
import Docxtemplater from 'docxtemplater';
import * as Echarts from 'echarts';
import ImageModule from 'docxtemplater-image-module-free';
import { saveAs } from 'file-saver';
import axios from 'axios';

const fileBtn = document.getElementById('fileBtn') as HTMLInputElement;

fileBtn.addEventListener('change', (e) => {
  const target = e.target as HTMLInputElement;
  if (target && target.files && target.files[0]) {
    const file = target.files[0];
    docx.renderAsync(file, document.getElementById('container')!).then(() => console.log('docx: finished'));
  }
});

function generateWord() {
  axios.request({ url: './customer_credit_report_template.docx', responseType: 'arraybuffer' }).then((res) => {
    console.log(res.data);
  });
  fetch('./customer_credit_report_template.docx')
    .then((res) => res.arrayBuffer())
    .then(async (res) => {
      console.log(res);
      const imageModOpts = {
        getImage(base64: string) {
          return base64ToArrayBuffer(base64);
        },
        getSize() {
          return [550, 300];
        },
      };
      const zip = new PizZip(res);
      const doc = new Docxtemplater(zip, {
        paragraphLoop: true,
        linebreaks: true,
        modules: [new ImageModule(imageModOpts)],
      });
      const charts = await Promise.all([
        createChart1(),
        createChart2(),
        createChart3(),
        createChart4(),
        createChart5(),
        createChart6(),
        createChart7(),
      ]);

      doc.render({
        company: '测试公司',
        reportNo: '1234567',
        reportTm: '2025-05-11',
        ...charts.reduce((acc, cur, index) => {
          acc[`chart${index + 1}`] = cur.chartInst.getDataURL({ backgroundColor: '#fff' });
          return acc;
        }, {}),
        // chart1: chart1.chartInst.getDataURL({ backgroundColor: '#fff' }),
        // chart2: chart2.chartInst.getDataURL({ backgroundColor: '#fff' }),
        // chart3: chart3.chartInst.getDataURL({ backgroundColor: '#fff' }),
        // chart4: chart4.chartInst.getDataURL({ backgroundColor: '#fff' }),
        // chart5: chart5.chartInst.getDataURL({ backgroundColor: '#fff' }),
        // chart6: chart6.chartInst.getDataURL({ backgroundColor: '#fff' }),
        // chart7: chart7.chartInst.getDataURL({ backgroundColor: '#fff' }),
      });
      charts.forEach((item) => {
        item.chartInst.dispose();
        item.dom.remove();
      });
      docx.renderAsync(doc.toBlob(), document.getElementById('docxContainer')!).then(() => console.log('docx: finished'));
      // const docxType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      // const out = doc.getZip().generate({
      //   type: 'blob',
      //   mimeType: docxType,
      // });
      // saveAs(out, 'generated.docx');

      // const myChart = Echarts.init(document.getElementById('echartsContainer'));

      // const option = {
      //   title: {
      //     text: 'ECharts 入门示例',
      //   },
      //   tooltip: {},
      //   legend: {
      //     data: ['销量'],
      //   },
      //   xAxis: {
      //     data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'],
      //   },
      //   yAxis: {},
      //   series: [
      //     {
      //       name: '销量',
      //       type: 'bar',
      //       data: [5, 20, 36, 10, 10, 20],
      //     },
      //   ],
      // };
      // myChart.on('finished', () => {
      //   const imgBase64 = myChart.getDataURL({ backgroundColor: '#fff' });

      //   const reader = new FileReader();
      //   reader.onload = (e) => {
      //     const content = e.target!.result;
      //     const imageOpts = {
      //       getImage(base64: string) {
      //         return base64ToArrayBuffer(base64);
      //       },
      //       getSize() {
      //         return [600, 400];
      //       },
      //     };
      //     const zip = new PizZip(content);
      //     const doc = new Docxtemplater(zip, {
      //       paragraphLoop: true,
      //       linebreaks: true,
      //       modules: [new ImageModule(imageOpts)],
      //     });

      //     // 替换模板中的变量
      //     doc.render({
      //       company: '测试公司',
      //       reportNo: '1234567',
      //       reportTm: '2025-05-11',
      //       img: imgBase64,
      //     });
      //     docx.renderAsync(doc.toBlob(), document.getElementById('container')!).then(() => console.log('docx: finished'));
      //     // const docxType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      //     // const out = doc.getZip().generate({
      //     //   type: 'blob',
      //     //   mimeType: docxType,
      //     // });
      //     // saveAs(out, 'generated.docx');
      //   };
      //   reader.readAsArrayBuffer(res);
      // });

      // // 使用刚指定的配置项和数据显示图表。
      // myChart.setOption(option);
    });
}
generateWord();

function base64ToArrayBuffer(base64: string) {
  // 1. 移除 Base64 URL 前缀（如果有）
  const base64Data = base64.split(',')[1] || base64;

  // 2. 将 Base64 字符串转换为二进制字符串
  const binaryString = atob(base64Data);

  // 3. 创建字节数组（Uint8Array）
  const length = binaryString.length;
  const bytes = new Uint8Array(length);

  // 4. 将每个字符的 Unicode 值存入字节数组
  for (let i = 0; i < length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }

  // 5. 返回 ArrayBuffer
  return bytes.buffer;
}

//近一年用电量趋势图
function createChart1(): Promise<{ chartInst: Echarts.ECharts; dom: HTMLDivElement }> {
  const dom = document.createElement('div');
  dom.style.width = '550px';
  dom.style.height = '300px';
  document.getElementById('echartsContainer2')!.appendChild(dom);
  const chartInst = Echarts.init(dom);

  const option = {
    title: {
      subtext: '单位：千瓦时',
    },
    color: ['#f6c207', '#57c6c6'],
    tooltip: {},
    legend: {
      bottom: 0,
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        interval: 0,
        rotate: 45,
      },
    },
    yAxis: {
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    series: [
      {
        type: 'line',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(246,194,7,0.6)', // 0% 处的颜色
              },
              {
                offset: 1,
                // color: 'transparent', // 100% 处的颜色
                color: '#fff', // 100% 处的颜色
              },
            ],
            global: false,
          },
        },
      },
      {
        type: 'line',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(87,198,198,0.6)', // 0% 处的颜色
              },
              {
                offset: 1,
                color: '#fff', // 100% 处的颜色
              },
            ],
            global: false,
          },
        },
      },
    ],
    dataset: {
      dimensions: ['time', '电量', '行业平均水准'],
      source: [
        { time: '202404', 电量: 99, 行业平均水准: 85.8 },
        { time: '202405', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202406', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202407', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202408', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202409', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202410', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202411', 电量: 30, 行业平均水准: 73.4 },
        { time: '202412', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202501', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202502', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202503', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202504', 电量: 83.1, 行业平均水准: 73.4 },
      ],
    },
  };
  return new Promise((resolve) => {
    chartInst.on('finished', () => {
      resolve({ chartInst, dom });
    });
    chartInst.setOption(option);
  });
}

//近三年用电量趋势图
function createChart2(): Promise<{ chartInst: Echarts.ECharts; dom: HTMLDivElement }> {
  const dom = document.createElement('div');
  dom.style.width = '550px';
  dom.style.height = '300px';
  document.getElementById('echartsContainer2')!.appendChild(dom);
  const chartInst = Echarts.init(dom);

  const option = {
    title: {
      subtext: '单位：千瓦时',
    },
    color: ['#f6c207'],
    tooltip: {},
    xAxis: {
      type: 'category',
      axisLabel: {
        interval: 1,
        rotate: 45,
      },
    },
    yAxis: {
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    series: [
      {
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(246,194,7,0.6)', // 0% 处的颜色
              },
              {
                offset: 1,
                // color: 'transparent', // 100% 处的颜色
                color: '#fff', // 100% 处的颜色
              },
            ],
            global: false,
          },
        },
      },
    ],
    dataset: {
      dimensions: ['time', '电量'],
      source: [
        { time: '202402', 电量: 89 },
        { time: '202403', 电量: 100 },
        { time: '202404', 电量: 99 },
        { time: '202405', 电量: 50.1 },
        { time: '202406', 电量: 60.1 },
        { time: '202407', 电量: 45.1 },
        { time: '202408', 电量: 83.1 },
        { time: '202409', 电量: 64.1 },
        { time: '202410', 电量: 70.1 },
        { time: '202411', 电量: 60 },
        { time: '202412', 电量: 83.1 },
        { time: '202501', 电量: 83.1 },
        { time: '202502', 电量: 83.1 },
        { time: '202503', 电量: 83.1 },
        { time: '202504', 电量: 83.1 },
      ],
    },
  };
  return new Promise((resolve) => {
    chartInst.on('finished', () => {
      resolve({ chartInst, dom });
    });
    chartInst.setOption(option);
  });
}

//同行业用电行为趋势对比
function createChart3(): Promise<{ chartInst: Echarts.ECharts; dom: HTMLDivElement }> {
  const dom = document.createElement('div');
  dom.style.width = '550px';
  dom.style.height = '300px';
  document.getElementById('echartsContainer2')!.appendChild(dom);
  const chartInst = Echarts.init(dom);

  const option = {
    title: {
      subtext: '单位：千瓦时',
    },
    color: ['#f6c207', '#57c6c6'],
    tooltip: {},
    legend: {
      right: 0,
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        // interval: 0,
        rotate: 45,
      },
    },
    yAxis: {
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    series: [
      {
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(246,194,7,0.6)', // 0% 处的颜色
              },
              {
                offset: 1,
                // color: 'transparent', // 100% 处的颜色
                color: '#fff', // 100% 处的颜色
              },
            ],
            global: false,
          },
        },
      },
      {
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(87,198,198,0.6)', // 0% 处的颜色
              },
              {
                offset: 1,
                color: '#fff', // 100% 处的颜色
              },
            ],
            global: false,
          },
        },
      },
    ],
    dataset: {
      dimensions: ['time', '行业月平均电量', '企业月电量'],
      source: [
        { time: '202404', 行业月平均电量: 99, 企业月电量: 85.8 },
        { time: '202405', 行业月平均电量: 83.1, 企业月电量: 73.4 },
        { time: '202406', 行业月平均电量: 83.1, 企业月电量: 73.4 },
        { time: '202407', 行业月平均电量: 83.1, 企业月电量: 73.4 },
        { time: '202408', 行业月平均电量: 83.1, 企业月电量: 73.4 },
        { time: '202409', 行业月平均电量: 83.1, 企业月电量: 73.4 },
        { time: '202410', 行业月平均电量: 83.1, 企业月电量: 73.4 },
        { time: '202411', 行业月平均电量: 30, 企业月电量: 73.4 },
        { time: '202412', 行业月平均电量: 83.1, 企业月电量: 73.4 },
        { time: '202501', 行业月平均电量: 83.1, 企业月电量: 73.4 },
        { time: '202502', 行业月平均电量: 83.1, 企业月电量: 73.4 },
        { time: '202503', 行业月平均电量: 83.1, 企业月电量: 73.4 },
        { time: '202504', 行业月平均电量: 83.1, 企业月电量: 73.4 },
      ],
    },
  };
  return new Promise((resolve) => {
    chartInst.on('finished', () => {
      resolve({ chartInst, dom });
    });
    chartInst.setOption(option);
  });
}

//近六个月电费趋势图
function createChart4(): Promise<{ chartInst: Echarts.ECharts; dom: HTMLDivElement }> {
  const dom = document.createElement('div');
  dom.style.width = '550px';
  dom.style.height = '300px';
  document.getElementById('echartsContainer2')!.appendChild(dom);
  const chartInst = Echarts.init(dom);

  const option = {
    title: {
      subtext: '单位：元',
    },
    color: ['#f6c207', '#57c6c6'],
    tooltip: {},
    legend: {
      bottom: 0,
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        interval: 0,
        // rotate: 45,
      },
    },
    yAxis: {
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    series: [
      {
        type: 'line',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(246,194,7,0.6)', // 0% 处的颜色
              },
              {
                offset: 1,
                // color: 'transparent', // 100% 处的颜色
                color: '#fff', // 100% 处的颜色
              },
            ],
            global: false,
          },
        },
      },
      {
        type: 'line',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(87,198,198,0.6)', // 0% 处的颜色
              },
              {
                offset: 1,
                color: '#fff', // 100% 处的颜色
              },
            ],
            global: false,
          },
        },
      },
    ],
    dataset: {
      dimensions: ['time', '电量', '行业平均水准'],
      source: [
        { time: '202411', 电量: 30, 行业平均水准: 73.4 },
        { time: '202412', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202501', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202502', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202503', 电量: 83.1, 行业平均水准: 73.4 },
        { time: '202504', 电量: 83.1, 行业平均水准: 73.4 },
      ],
    },
  };
  return new Promise((resolve) => {
    chartInst.on('finished', () => {
      resolve({ chartInst, dom });
    });
    chartInst.setOption(option);
  });
}

//近3年电费趋势图
function createChart5(): Promise<{ chartInst: Echarts.ECharts; dom: HTMLDivElement }> {
  const dom = document.createElement('div');
  dom.style.width = '550px';
  dom.style.height = '300px';
  document.getElementById('echartsContainer2')!.appendChild(dom);
  const chartInst = Echarts.init(dom);

  const option = {
    title: {
      subtext: '单位：元',
    },
    color: ['#f6c207'],
    tooltip: {},
    xAxis: {
      type: 'category',
      axisLabel: {
        interval: 1,
        rotate: 45,
      },
    },
    yAxis: {
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    series: [
      {
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(246,194,7,0.6)', // 0% 处的颜色
              },
              {
                offset: 1,
                // color: 'transparent', // 100% 处的颜色
                color: '#fff', // 100% 处的颜色
              },
            ],
            global: false,
          },
        },
      },
    ],
    dataset: {
      dimensions: ['time', '电量'],
      source: [
        { time: '202402', 电量: 89 },
        { time: '202403', 电量: 100 },
        { time: '202404', 电量: 99 },
        { time: '202405', 电量: 50.1 },
        { time: '202406', 电量: 60.1 },
        { time: '202407', 电量: 45.1 },
        { time: '202408', 电量: 83.1 },
        { time: '202409', 电量: 64.1 },
        { time: '202410', 电量: 70.1 },
        { time: '202411', 电量: 60 },
        { time: '202412', 电量: 83.1 },
        { time: '202501', 电量: 83.1 },
        { time: '202502', 电量: 83.1 },
        { time: '202503', 电量: 83.1 },
        { time: '202504', 电量: 83.1 },
      ],
    },
  };
  return new Promise((resolve) => {
    chartInst.on('finished', () => {
      resolve({ chartInst, dom });
    });
    chartInst.setOption(option);
  });
}

//近六个缴费行为信息
function createChart6(): Promise<{ chartInst: Echarts.ECharts; dom: HTMLDivElement }> {
  const dom = document.createElement('div');
  dom.style.width = '550px';
  dom.style.height = '300px';
  document.getElementById('echartsContainer2')!.appendChild(dom);
  const chartInst = Echarts.init(dom);

  const option = {
    title: {},
    color: ['#f6c207'],
    tooltip: {},
    radar: {
      shape: 'circle',
      splitArea: {
        show: false,
      },
      indicator: [{ name: '供电局缴费' }, { name: '银行缴费' }, { name: '第三方缴费' }, { name: '自助缴费' }],
    },
    series: [
      {
        type: 'radar',
        data: [
          {
            value: [1000, 3000, 2000, 1120],
          },
        ],
      },
    ],
  };
  return new Promise((resolve) => {
    chartInst.on('finished', () => {
      resolve({ chartInst, dom });
    });
    chartInst.setOption(option);
  });
}
//信用影响因素
function createChart7(): Promise<{ chartInst: Echarts.ECharts; dom: HTMLDivElement }> {
  const dom = document.createElement('div');
  dom.style.width = '550px';
  dom.style.height = '300px';
  document.getElementById('echartsContainer2')!.appendChild(dom);
  const chartInst = Echarts.init(dom);

  const option = {
    title: {},
    color: ['#f6c207', '#57c6c6'],
    legend: {
      data: ['得分', '满分'],
      itemWidth: 10,
      itemHeight: 10,
      bottom: 0,
    },
    tooltip: {},
    radar: {
      shape: 'circle',
      center: ['50%', '60%'],
      splitArea: {
        show: false,
      },
      splitLine: {
        show: false,
      },
      axisName: {
        color: '#000',
        backgroundColor: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 1,
          y2: 0,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(87, 198, 198, 0.6)', // 0% 处的颜色
            },
            {
              offset: 1,
              // color: 'transparent', // 100% 处的颜色
              color: '#fff', // 100% 处的颜色
            },
          ],
          global: false,
        },
        padding: [10, 20],
        borderRadius: 20,
      },
      indicator: [{ name: '缴费行为特征' }, { name: '企业供应关系' }, { name: '用电行为特征' }],
    },
    series: [
      {
        type: 'radar',
        areaStyle: {},
        data: [
          {
            name: '得分',
            value: [30, 40, 30, 60],
            label: {
              show: true,
            },
          },
          {
            name: '满分',
            value: [100, 100, 100, 100],
          },
        ],
      },
    ],
  };
  return new Promise((resolve) => {
    chartInst.on('finished', () => {
      resolve({ chartInst, dom });
    });
    chartInst.setOption(option);
  });
}
